package com.lecture.java8.file;

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;

/**
 * 操作文件夹工具类
 * @author luyn
 * @date 2024/03/06
 */
public class FolderDemo {

    public static void main(String[] args) {
        String content = "Hello, World!\nThis is a sample text.";
        String filePath = "D:\\study\\py\\logs\\example.txt";

        try {
            writeStringToFile(content, filePath);
            writeStringToFile(content, filePath);
            System.out.println("Content has been written to " + filePath + " successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void writeStringToFile(String content, String filePath) throws IOException {
        Path path = Paths.get(filePath);
        Files.write(path, content.getBytes(),StandardOpenOption.APPEND);
    }


    public static void main2(String[] args) {
        try {
            String folderPath = "D:\\study\\py";
            // 打开文件夹路径
            Path directory = Paths.get(folderPath);
            // 获取文件夹下的唯一子文件夹
            Path subFolder = getSubFolder(directory);
            if (subFolder != null) {
                // 遍历子文件夹内的所有文件，获取文件信息
                Files.walkFileTree(subFolder, new SimpleFileVisitor<Path>() {
                    @Override
                    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                        printFileInfo(file, attrs);
                        return FileVisitResult.CONTINUE;
                    }
                });
            } else {
                System.out.println("No subfolder found in the specified directory.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void folderDemo() throws IOException {
        String folderPath = "D:\\study\\py";
        Path path = Paths.get(folderPath);
        Files.walkFileTree(path,new MyFileVisitor());
    }

    public static Path getSubFolder(Path directory) throws IOException {
        try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(directory)) {
            for (Path path : directoryStream) {
                if (Files.isDirectory(path)) {
                    return path; // 返回文件夹路径
                }
            }
        }
        return null; // 没有找到子文件夹
    }

    public static void printFileInfo(Path filePath, BasicFileAttributes attr) {
        System.out.println("File: " + filePath.getFileName());
        System.out.println("Size: " + attr.size());
        System.out.println("Creation Time: " + attr.creationTime());
        System.out.println("Last Modified Time: " + attr.lastModifiedTime());
        System.out.println("Is Directory: " + attr.isDirectory());
        System.out.println("Is Regular File: " + attr.isRegularFile());
        System.out.println();
    }
}
